<template>
  <Row type="flex" justify="center" align="middle">
    <Col>
      <Card shadow style="width:580px;margin-top:30%;">
        <Form ref='pwdForm' :model='pwdForm' :rules='pwdFormRules' :label-width="120" inline>
          <FormItem label="旧密码" prop="oldPwd">
            <Input type="password" v-model="pwdForm.oldPwd" autocomplete="new-password"></Input>
          </FormItem>
          <FormItem label="新密码" prop="newPwd">
            <Input type="password" v-model="pwdForm.newPwd"></Input>
          </FormItem>
          <FormItem label="确认密码" prop="confirmPwd">
            <Input type="password" v-model="pwdForm.confirmPwd"></Input>
          </FormItem>
          <div style="text-align:center">
            <Button type="primary" @click="submitForm">提交</Button>
          </div>
        </Form>
      </Card>
    </Col>
  </Row>

</template>

<script>
export default {
  data () {
    const validatePwd = (rule, value, callback) => {
      if (!value || value === null || value === '') {
        callback(new Error('新密码不能为空'))
      } else {
        if (this.pwdForm.confirmPwd && this.pwdForm.confirmPwd !== '') {
          // 对第二个密码框单独验证
          this.$refs.pwdForm.validateField('confirmPwd')
        }
        callback()
      }
    }
    const validateConfirmPwd = (rule, value, callback) => {
      if (value !== this.pwdForm.newPwd) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    return {
      $ajax: null,
      pwdForm: {},
      pwdFormRules: {
        oldPwd: [{
          required: true,
          message: '旧密码不能为空',
          trigger: 'blur'
        }],
        newPwd: [{
          required: true,
          validator: validatePwd,
          trigger: 'blur'
        }],
        confirmPwd: [{
          required: true,
          validator: validateConfirmPwd,
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    submitForm () {
      var vm = this
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          var params = this.pwdForm
          vm.$ajax
            .post(
              this.$appContext.marvels_core_system + 'system/service/editPassword',
              params
            )
            .then(re => {
              var data = re.data
              var code = data.code
              var message = data.message
              if (code !== 'success') {
                this.$Message.warning(message)
                return
              }
              alert('密码修改完成，请重新登录')
              sessionStorage.clear()
              this.$router.push({
                name: 'login'
              })
            })
            .catch(er => {})
        }
      })
    }
  },
  created () {
    this.$ajax = this.$util.ajax()
  }
}
</script>
